<template>
  <view class="ai-chat-container">
    <!-- 顶部导航 -->
    <!-- <view class="chat-header">
      <view class="back-btn" @click="goBack">←</view>
      <view class="title">智能对话</view>
    </view> -->
	
	<my-navbar leftText="问题反馈" leftIcon="arrow-left" :custom="false" bgColor="#ffffff" :autoBack="true"
					leftIconSize="40" />
    
    <!-- 消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-top="scrollTop"
      @scrolltolower="loadMoreHistory"
    >
      <view v-for="(msg, index) in messageList" :key="index" class="message-item">
        <!-- 用户消息 -->
        <view v-if="msg.role === 'user'" class="user-message">
          <image :src="userlogo" class="avatar" />
          <view class="content">{{ msg.content }}</view>
        </view>
        
        <!-- 消息 -->
        <view v-if="msg.role === 'assistant'" class="ai-message">
          <image src="/static/index/store.png" class="avatar" />
          <view class="content">{{ msg.content }}</view>
          <!-- 加载中动画 -->
          <view v-if="msg.loading" class="loading">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <input 
        v-model="inputContent" 
        class="input" 
        placeholder="请输入问题..."
        @confirm="sendMessage"
      />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  data() {
    return {
      inputContent: '',
      scrollTop: 0,
      sessionId: '',
      messageList: [],
	  userInfo: {},
	  phone: undefined,
	  isLogin: false,
	  userlogo:'',
    }
  },
  onLoad() {
    this.initSession()
	var isLogin = uni.getStorageSync('isLogin')
	if (isLogin == true) {
		this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
		console.log(this.userInfo)
		console.log(this.userInfo.nickName)
		this.isLogin = isLogin
		var isPhone = uni.getStorageSync('isPhone')
		if (isPhone != null && isPhone != '') {
			this.phone = th.userInfo.phone
		} else {
			this.phone = '未提供手机号'
		}
		console.log(this.phone)
		this.userlogo=this.userInfo.avatarUrl
	} else {
		console.log("未登录")
		this.userlogo='/static/index/one.png'
		this.userInfo = {}
		this.isLogin = false
	}
  },
  methods: {
    ...mapMutations(['setSessionId', 'addMessage']),
    
    // 初始化会话
    async initSession() {
      // 从本地存储获取会话ID，没有则创建新会话
      const storedSessionId = uni.getStorageSync('aiSessionId')
      
      if (storedSessionId) {
        this.sessionId = storedSessionId
        // 加载历史消息
        await this.loadHistoryMessages()
      } else {
        await this.createNewSession()
      }
    },
    
    // 创建新会话
    async createNewSession() {
      try {
        const res = await uni.request({
          url: uni.$u.http.config.baseURL + '/event/ai/add/session',
          method: 'post',
          data: { title: '对话' }
        })
        
        if (res.code === 200) {
          this.sessionId = res.data.id
          uni.setStorageSync('aiSessionId', this.sessionId)
        }
      } catch (err) {
        console.error('创建会话失败', err)
      }
    },
    
    // 加载历史消息
    async loadHistoryMessages() {
      try {
        const res = await uni.request({
          url: uni.$u.http.config.baseURL+'/event/ai/detail/list',
          method: 'get',
          data: { sessionId: this.sessionId }
        })
        
        if (res.code === 200) {
          this.messageList = res.rows || []
          this.scrollToBottom()
        }
      } catch (err) {
        console.error('加载历史消息失败', err)
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.inputContent.trim()) return
      
      // 添加用户消息到列表
      const userMsg = {
        role: 'user',
        content: this.inputContent.trim(),
        timestamp: Date.now()
      }
      this.messageList.push(userMsg)
      this.inputContent = ''
      this.scrollToBottom()
      
      // 添加加载状态
      const aiMsgIndex = this.messageList.length
      this.messageList.push({
        role: 'assistant',
        content: '',
        loading: true //显示加载动画
      })
      this.scrollToBottom()
      
    //   try {
    //     // 使用uni.request的stream模式处理SSE
    //     const task = uni.request({
    //       // url: `http://localhost:8080/event/ai/streamChat?text=${encodeURIComponent(userMsg.content)}&sessionId=${this.sessionId}`,
    //       url: `http://localhost:8080/event/ai/streamChat?text=${encodeURIComponent(userMsg.content)}&sessionId=1`,
		  // method: 'get',
    //       responseType: 'stream',
    //       success: (response) => {
    //         const stream = response.data
    //         stream.on('data', (chunk) => {
    //           // 解析SSE格式
    //           const text = chunk.toString().replace(/^data: /, '').trim()
    //           if (text) {
    //             this.messageList[aiMsgIndex].content += text
    //             this.scrollToBottom()
    //           }
    //         })
    //         stream.on('end', () => {
    //           this.messageList[aiMsgIndex].loading = false
    //         })
    //       },
    //       fail: (err) => {
    //         console.error('发送消息失败', err)
    //         this.messageList[aiMsgIndex].content = '抱歉，请求失败，请重试'
    //         this.messageList[aiMsgIndex].loading = false
    //       }
    //     })
    //   } catch (err) {
    //     console.error('发送消息异常', err)
    //     this.messageList[aiMsgIndex].content = '抱歉，请求异常，请重试'
    //     this.messageList[aiMsgIndex].loading = false
    //   }
	
	try {
	        // 改为普通HTTP请求（非流式）
	        const [err, res] = await uni.request({
	          url: uni.$u.http.config.baseURL+`/event/ai/completeChat`, // 后端新接口（非流式）
	          method: 'post', // 建议用post，避免get参数长度限制
	          data: { 
	            text: userMsg.content, 
				sessionId: 1 ,
	            // sessionId: this.sessionId 
	          }
	        })
	
	        if (err) {
	          throw new Error('网络请求失败')
	        }
			console.log(res)
			console.log(res.data.code)
			console.log(res.data.data.content)
	        // 假设后端返回格式：{ code: 200, data: { content: '完整回复内容' } }
	        if (res.data.code === 200) {
				// 提取有效内容
				  const rawContent = res.data.data.content;
				  // 使用正则表达式匹配最后一组标签之间的内容
				  const regex = /([\s\S]*?)<\/think>/g;
				  const matches = [];
				  let match;
				  
				  // 收集所有匹配的内容
				  while ((match = regex.exec(rawContent)) !== null) {
					  console.log(match)
					  if (match[1]){
						  matches.push(match[1].trim());
					  }
						console.log(matches)
				  }
				  
				  console.log(matches)
				  // 核心修正：如果存在<\/think>标签，真实回复是最后一个<\/think>之后的内容
				    // 查找最后一个<\/think>的位置
				    const lastThinkIndex = rawContent.lastIndexOf('</think>');
				    let displayContent;
				    
				    if (lastThinkIndex !== -1) {
				      // 截取最后一个<\/think>之后的内容（+8是""的长度）
				      displayContent = rawContent.substring(lastThinkIndex + 8).trim();
				    } else {
				      // 没有找到标签，使用原始内容或匹配到的最后一项
				      displayContent = matches.length > 0 ? matches[matches.length - 1] : rawContent;
				    }
				    
				    console.log('最终显示内容：', displayContent);
				  
	          // 更新消息内容，关闭加载状态
	          // this.messageList[aiMsgIndex] = {
	          //   role: 'assistant',
	          //   content: displayContent,
	          //   loading: false
	          // }
			  // 使用$set确保响应式更新
			  this.$set(this.messageList, aiMsgIndex, {
			    role: 'assistant',
			    content: displayContent,
			    loading: false
			  })
			  
	        } else {
	          throw new Error(res.data.msg || '服务器处理失败')
	        }
	      } catch (err) {
	        console.error('发送消息失败', err)
	        // 错误处理
	        // this.messageList[aiMsgIndex] = {
	        //   role: 'assistant',
	        //   content: `抱歉，${err.message}，请重试`,
	        //   loading: false
	        // }
			this.$set(this.messageList, aiMsgIndex, {
			  role: 'assistant',
			  content: `抱歉，${err.message}，请重试`,
			  loading: false
			})
			
	      } finally {
	        this.scrollToBottom() // 确保滚动到底部
	      }
	
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999
      })
    },
    
    // 返回上一页
    goBack() {
      const backUrl = uni.getStorageSync('aiChatBackUrl') || '/pages/index/index'
      uni.navigateTo({ url: backUrl })
    },
    
    // 加载更多历史（可选）
    loadMoreHistory() {
      // 实现历史消息分页加载逻辑
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-header {
  height: 100rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  font-size: 36rpx;
  margin-right: 30rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.message-list {
  flex: 1;
  padding: 30rpx;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 40rpx;
  display: flex;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .content {
  background-color: #007aff;
  color: white;
  border-radius: 20rpx 20rpx 0 20rpx;
}

.ai-message .content {
  background-color: white;
  border-radius: 20rpx 20rpx 20rpx 0;
}

.content {
  max-width: 600rpx;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  line-height: 1.5;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.loading {
  display: flex;
  gap: 10rpx;
  padding: 20rpx;
}

.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #999;
  animation: loading 1.4s infinite ease-in-out both;
}

.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }

@keyframes loading {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.input-area {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.send-btn {
  width: 120rpx;
  height: 80rpx;
  margin-left: 20rpx;
  background-color: #007aff;
  color: white;
  border-radius: 40rpx;
  font-size: 28rpx;
  line-height: 80rpx;
}
</style>